import os.path
import time
import requests
import subprocess

import Common.connect_to_device
from Common.connect_to_device import *
from Common.hande_device import HandleDevices
from influxdb_client import Point
from Common.handle_log import do_log
from Common.handle_influxdb import InfluxDBHandler
from Common.ding_ding import send_dingtalk_message
from Common.global_data import GlobalData
do_devices = HandleDevices(pkgName=package_name)
do_influxdb = InfluxDBHandler()

command = "adb shell cat /proc/cpuinfo"

process = subprocess.Popen(['cmd', '/c', command],
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           text=True)
stdout, stderr = process.communicate()
cpu_number = stdout.count("processor	:")

apm_pid_main, pid_main, apm_pid_copilot, pid_copilot = do_devices.handle_main_device(deviceId_001=device_1)
wrong = 500
if os.path.exists("main_logcat.txt"):
    os.remove("main_logcat.txt")
while True:
    # 准备数据点列表

    measurements = []
    if pid_main:

        time.sleep(1)
        try:
            device_001_main_cpu = do_devices.get_cpu(apm_pid_main, cpu_number)["appCpuRate"]
            device_001_main_mem = do_devices.get_mem(apm_pid_main)
        except:
            device_001_main_cpu, device_001_main_mem = None, None
        if isinstance(device_001_main_cpu, float) and isinstance(device_001_main_mem, float):

            pid_main = int(pid_main)
            measurements_m = [
                Point("device_001").tag("pid", "main_pid").field("cpu", device_001_main_cpu),
                Point("device_001").tag("pid", "main_pid").field("mem", device_001_main_mem),
                Point("device_001").tag("pid", "main_pid").field("pid", pid_main)
            ]
            do_log.info(
                f"main_pid:{pid_main},main_cpu:{device_001_main_cpu},main_mem:{device_001_main_mem},main_table:{bucket_name}")
            measurements.extend(measurements_m)
        else:
            wrong -= 1
            do_log.error(f"获取数据device_main不是浮点类型，不满足要求，跳过")
    if pid_copilot:
        time.sleep(1)
        try:
            device_001_copilot_cpu = do_devices.get_cpu(apm_pid_copilot, cpu_number)["appCpuRate"]
            device_001_copilot_mem = do_devices.get_mem(apm_pid_copilot)
        except:
            device_001_copilot_cpu, device_001_copilot_mem = None, None
        if isinstance(device_001_copilot_cpu, float) and isinstance(device_001_copilot_mem, float):

            time.sleep(1)
            pid_copilot = int(pid_copilot)
            measurements_c = [
                Point("device_001").tag("pid", "main_pid").field("cpu_c", device_001_copilot_cpu),
                Point("device_001").tag("pid", "main_pid").field("mem_c", device_001_copilot_mem),
                Point("device_001").tag("pid", "main_pid").field("pid_c", pid_copilot)
            ]
            do_log.info(
                f"copilot_pid:{pid_copilot},copilot_cpu:{device_001_copilot_cpu},copilot_mem:{device_001_copilot_mem},copilot_table:{bucket_name}")
            measurements.extend(measurements_c)
        else:
            wrong -= 1
            do_log.error(f"获取数据device_copilot不是浮点类型，不满足要求，跳过")
    if len(measurements) > 0:
        result = do_influxdb.write_mul_data(measurements=measurements)
        if result:
            do_log.info("数据库写入成功")
        else:
            do_log.error("数据库写入失败")
    else:
        do_log.error("数据为空")
        wrong -= 1
    if wrong < 0:
        with open("main_logcat.txt", "w") as f:
            f.write("A 已完成")
        do_log.error("写入数据监控暂停，生成通知文件")
        do_log.error("数据为空超过300次，监控暂停")
        # 发送通知
        title = f"性能测试存在问题，数据为空超过{wrong}次，监控暂停，请注意"
        send_dingtalk_message(title)
        break
